//
//  AppDelegate.m
//  HiMaster3
//
//  Created by jinghao on 15/12/7.
//  Copyright © 2015年 jinghao. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import <CoreSpotlight/CoreSpotlight.h>
#import "ViewModelServicesImpl.h"
#import "WXApi.h"
#import "GeTuiSdk.h"
#import "UPPaymentControl.h"
#import "UserClient.h"
#import "AdvertisementView.h"
#import "SlideMainViewController.h"
//#import <JSPatch/JSPatch.h>
#import "MasterNotificationView.h"
#import "AppAdView.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "Bugout/Bugout.h"
#import "RealReachability.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<WXApiDelegate,GeTuiSdkDelegate,AMapLocationManagerDelegate>
@property (nonatomic, strong) ViewModelServicesImpl *services;
@property (nonatomic,strong)AdvertisementView *advertView;
@property (nonatomic,assign)BOOL appRunning;
@property (nonatomic,strong)NSURL *needOpenUrl;
@property (nonatomic,strong)NSURL *trackViewUrl;
@property (nonatomic,strong)NSDictionary *needNotificationInfo;
@property (nonatomic,assign)BOOL appNewVersion;
@property (nonatomic, strong) AMapLocationManager * locationManager;
@property (nonatomic, assign) BOOL appFirstRun; // app第一次登陆
@property (nonatomic, assign) BOOL manuLogin;   // 手动登陆

//@property (nonatomic,assign) NSInteger count;
//@property (nonatomic,assign) BOOL canLock;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"==== stat app start ====");
    
//    //Bugout配置
////    [Bugout init:@"81ba44b480cb8a792079a8319c88074e" channel:nil config:[BugoutConfig defaultConfig]];
//    [self newAppLocationVersion];
//    NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
//     @weakify(self);
//    if (![LYAuthorizedMaster checkPushNotificationAuthority]) {
//        NSString* appCode = [userDefault objectForKey:FristGetNotificationKey];
//        if (appCode==nil)
//        {
//            [userDefault setObject: App_Version forKey:FristGetNotificationKey];
//            [userDefault synchronize];
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"关闭通知，便很可能收不到来自您女神的安危通知，请务必谨慎操作！" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
//            [alertView show];
//            [alertView.rac_buttonClickedSignal subscribeNext:^(NSNumber *index) {
//                @strongify(self);
//                [self registerRemoteNotification];
//            }];
//        }else{
//             [self registerRemoteNotification];
//        }
//    }else{
//        [self registerRemoteNotification];
//    }
//    
//
//    
////    [self initAppConfig];
////    self.services = [[ViewModelServicesImpl alloc] init];
////    高德地图apikey配置
//    [[AMapServices sharedServices] setEnableHTTPS:YES];
//    [AMapServices sharedServices].apiKey = GaodeMapKey;
//    [self.locationManager startUpdatingLocation];
//    [self registerUrl];
//    [self initUmnegSDK];
////    [JSPatch startWithAppKey:JSPATCH_APPKEY];
//    [GLobalRealReachability startNotifier];
//    [self startDetectCurrentReachabilityStatus];
////    [WXApi registerApp:WeixinScheme withDescription:@"demo 2.0"];
//    
//    self.needNotificationInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
//    if (self.needNotificationInfo==nil)
//    {
//        self.needNotificationInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsLocalNotificationKey"];
//    }
//    
//    [GeTuiSdk resetBadge]; //重置角标计数
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // APP 清空角标
//    [self checkVersionForAppstore];
//    NSLog(@"==== stat app end ====");
////    设置语音播放为扬声器模式
////    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
////    [[AVAudioSession sharedInstance] setActive:YES error:nil];
//    
////    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
////    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
//
//    
////设置语音播放为扬声器模式
////    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
////    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    return YES;
    

}




//- (void)volumeChanged:(NSNotification *)notification
//{
//    // service logic here.
//    self.count ++;
//    if (!self.canLock) {
//        self.canLock = !self.canLock;
//        [self performSelector:@selector(emergencyHelp) withObject:nil afterDelay:1.0];
//    }
//    NSLog(@"noti");
//}

//- (void)emergencyHelp{
//    if (self.count >= 2) {
//        self.count = 0;
//        if ([[NSUserDefaults standardUserDefaults] objectForKey:CallHelpFirstKey]) {
//            if (![[UserClient sharedUserClient].currentVC isEqualToString:@"GPSNaviViewController"]) {
//                [self openHelp];
//            }
//        }
//    }else{
//        self.count = 0;
//    }
//    self.canLock = NO;
//}
//-(void)openHelp{
//    [LYAuthorizedMaster LoginCheckSuccess:^{
//        [LYAuthorizedMaster pushNotificationAuthorityCheckSuccess:^{
//            if([UserClient sharedUserClient].openTypeId){
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"DoubleClickNotification" object:nil];
//                return;
//            }
//            @weakify(self)
//            [self getMyContract:^(void){
//                @strongify(self)
//                [self openHelpAfter];
//            }];
//        } fail:^{
//        
//        }];
//    } fail:^{
//        
//    }];
//}
//-(void)openHelpAfter{
//    @weakify(self)
//    [[[HttpManagerCenter sharedHttpManager] wantHelpWithresultClass:nil] subscribeNext:^(BaseModel *model){
//        @strongify(self)
//        if(model.code==200){
//            [[UserClient sharedUserClient] setOpenTypeStatus:@[@"2", model.data[@"id"]]];
//            [self presentViewControllerAndPostNotification];
//        }else{
//            [[MasterUrlManager shareMasterUrlManager].currentVC hiddenHUDWithString:model.message error:NO];
//        }
//    }];
//}
//
//-(void)getMyContract:(GetContractSuccessBlock)block{
//    if([UserClient sharedUserClient].firstContractName){
//        block();
//    }else{
//        [[[HttpManagerCenter sharedHttpManager] queryContactList:nil] subscribeNext:^(BaseModel *model) {
//            NSMutableArray *array = [NSMutableArray new];
//            if(model.code==200){
//                array = model.data;
//                if(array.count != 0){
//                    NSDictionary *contactDic = array.firstObject;
//                    [[UserClient sharedUserClient] changeFirstContractName:contactDic[@"name"]];
//                    block();
//                }else{
//                    UIStoryboard *HelpStory = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
//                    BaseViewController * BaseViewController = [HelpStory instantiateViewControllerWithIdentifier:@"MyContactVC"];
//                    [[MasterUrlManager shareMasterUrlManager].currentVC pushViewController:BaseViewController animated:YES];
//                }
//            }else{
//                [[MasterUrlManager shareMasterUrlManager].currentVC hiddenHUDWithString:model.message error:NO];
//            }
//        }];
//    }
//}
//
//
//
//-(void)presentViewControllerAndPostNotification{
////    NSLog(@"%@",);
//    if(![[NSString stringWithFormat:@"%@",[MasterUrlManager shareMasterUrlManager].currentVC.class] isEqualToString:@"CallHelpViewController"]){
////        UIViewController *mainVct = [UIStoryboard viewController:@"GuardMe" identifier:@"CenterAndDeterenceRootNAV"];
////        [[MasterUrlManager shareMasterUrlManager].currentVC presentViewController:mainVct animated:YES completion:^(void){
////            [[NSNotificationCenter defaultCenter] postNotificationName:@"DoubleClickNotification" object:nil];
////        }];
//        [[MasterUrlManager shareMasterUrlManager].currentVC.navigationController popToRootViewControllerAnimated:YES];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"DoubleClickNotification" object:nil];
//    }else{
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"DoubleClickNotification" object:nil];
//    }
//}
- (void)applicationWillResignActive:(UIApplication *)application {
    [GeTuiSdk resetBadge]; //重置角标计数
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // APP 清空角标
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    if ([UserClient sharedUserClient].password.length == 4) {
        UIViewController *mainVct = [UIStoryboard viewController:@"Mine" identifier:@"AlterSecurityCideViewController"];
        self.window.rootViewController = mainVct;
        [self.window makeKeyAndVisible];
    }
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


///**
// 这里处理新浪微博SSO授权进入新浪微博客户端后进入后台，再返回原来应用
// */
//- (void)applicationDidBecomeActive:(UIApplication *)application
//{
//    [UMSocialSnsService  applicationDidBecomeActive];
////    [JSPatch sync];
//}
//
//- (void)newAppLocationVersion{
//    NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
//    NSString* appCode = [userDefault objectForKey:FristStartAppVersionKey];
//    if (appCode==nil || ![App_Version isEqualToString:appCode])//新版本
//    {
//        self.appNewVersion = YES;
//    }else{
//        self.appNewVersion = NO;
//    }
//}
//
//
//#pragma mark -- URL处理
//
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
//    return  [self openApplicationWithURL:url];
//}
//
//
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options {
//    return  [self openApplicationWithURL:url];
//}
//
///**
// 这里处理新浪微博SSO授权之后跳转回来，和微信分享完成之后跳转回来
// */
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    return  [self openApplicationWithURL:url];
//}
//
//- (BOOL)openApplicationWithURL:(NSURL *)url{
//    
//    if ([url.scheme isEqualToString:UnionpayScheme]) {//银联支付
//         [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
//             NSLog(@"UPPaymentControl  result = %@",data);
//             //结果code为成功时，先校验签名，校验成功后做后续处理
//             if([code isEqualToString:@"success"]) {
//                 //判断签名数据是否存在
//                 if(data == nil){
//
//                 }
//                 [self paySuccess:1];
//             }else if ([code isEqualToString:@"fail"]){
//                 alertShowMessage(@"支付失败");  
//             }else if ([code isEqualToString:@"cancel"]){
//                 alertShowMessage(@"您已取消了支付");
//             }
//         }];
//    }else if ([url.scheme isEqualToString:AlipayScheme]){//支付支付
//        //TODO 支付宝支付处理
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"reslut = %@   %@",resultDic,resultDic[@"memo"]);
//            NSString* resultStatus = resultDic[@"resultStatus"];
//            if ([resultStatus isEqualToString:@"9000"]) {
//                [self paySuccess:2];
//            }else{
//                alertShowMessage(@"支付失败");
//            }
//        }];
//    }else if([url.scheme isEqualToString:WeixinScheme]){//微信支付
//         [WXApi handleOpenURL:url delegate:self];
//    }else if([url.scheme isEqualToString:@"safelady"]||[url.scheme hasPrefix:@"https"]||[url.scheme hasPrefix:@"http"]){
//        if(self.appRunning){
//            if ([[MasterUrlManager shareMasterUrlManager] isPrivateUrl:url]) {
//                if ([UserClient sharedUserClient].rawLogin) {
//                    [[MasterUrlManager shareMasterUrlManager] openURL:url];
//                }
//            }else{
//                [[MasterUrlManager shareMasterUrlManager] openURL:url];
//            }
//        }else{
//            self.needOpenUrl = url;
//        }
//    }
//    return [UMSocialSnsService handleOpenURL:url wxApiDelegate:self];
//}
//
//- (void)paySuccess:(NSInteger)type{
//    [[NSNotificationCenter defaultCenter] postNotificationName:MasterPayResultNotification object:nil];
//}
#pragma mark -- 版本检查更新
//- (void)checkVersionForAppstore{
//    先注册，待上线前换成自己的后 再打开注释
//    NSString *updateType = [NSUserDefaults stringForKey:MasterUpdateAppType];
//    if (updateType && updateType.integerValue==1) {
//        return ;
//    }
//    NSString* versionUrl = [NSString stringWithFormat:@"https://itunes.apple.com/cn/lookup?id=%@",MasterAppId];
//    __weak typeof(self) weakSelf = self;
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSData* versionData = [NSData dataWithContentsOfURL:[NSURL URLWithString:versionUrl]];
//        if(versionData){
//            id appData = [NSJSONSerialization JSONObjectWithData:versionData options:NSJSONReadingMutableContainers error:nil];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                NSArray *versionsInAppStore = [[appData valueForKey:@"results"] valueForKey:@"version"];
//                if ( ![versionsInAppStore count] ) { // No versions of app in AppStore
//                  
//                    
//                } else {
//                    
//                    NSString *currentAppStoreVersion = [versionsInAppStore objectAtIndex:0];
//                    NSArray *versionsReleaseNotes = [[appData valueForKey:@"results"] valueForKey:@"releaseNotes"];
//                    
//                    NSString *currentAppStoreReleaseNotes = [versionsReleaseNotes objectAtIndex:0];
//                    
//                    NSArray *versionsTrackViewUrl = [[appData valueForKey:@"results"] valueForKey:@"trackViewUrl"];
//                    
//                    if ([App_Version compare:currentAppStoreVersion options:NSNumericSearch] == NSOrderedAscending) {
//                        weakSelf.trackViewUrl = [NSURL URLWithString:[versionsTrackViewUrl objectAtIndex:0]];
//                        [weakSelf showAlertWithAppStoreVersion:currentAppStoreReleaseNotes];
//                    }
//                }
//                NSLog(@"==== version %@",appData);
//            });
//        }
//    });
//}

//- (void)showAlertWithAppStoreVersion:currentAppStoreVersion{
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"发现新版本"
//                                                        message:currentAppStoreVersion
//                                                       delegate:self
//                                              cancelButtonTitle:@"立即更新"
//                                              otherButtonTitles:@"残忍决绝",@"下次再说", nil];
//    
//    [alertView show];
//    @weakify(self);
//    [alertView.rac_buttonClickedSignal subscribeNext:^(NSNumber *index) {
//        @strongify(self);
//        if (index.integerValue==2) {
//        }else if (index.integerValue==1){
//            [NSUserDefaults setObject:@"1" forKey:MasterUpdateAppType];
//        }else if (index.integerValue==0){
//            [[UIApplication sharedApplication] openURL:self.trackViewUrl];
//        }
//    }];
//}

#pragma mark -- 推送通知

////注册通知
//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
//{
//    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
//    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
//    [NSUserDefaults setArcObject:token forKey:APP_DeviceToken_Key];
//    //向个推服务器注册deviceToken
//    [GeTuiSdk registerDeviceToken:token];
//}
//
//- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
//{
//    NSLog(@"====didFailToRegisterForRemoteNotificationsWithError===========%@",error);
//}
//
///** 已登记用户通知 */
//- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
//    // 注册远程通知（推送）
//    [application registerForRemoteNotifications];
//}
//
//- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//    /// Background Fetch   SDK
//    [GeTuiSdk resume];
//    completionHandler(UIBackgroundFetchResultNewData);
//}
///**
// *  注册通知
// */
//- (void)registerRemoteNotification
//{
//    //注册个推服务
//    NSString *deviceTokenId = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
//    if (deviceTokenId) {
//        [NSUserDefaults setArcObject:deviceTokenId forKey:APP_DeviceToken_Key];
//    }
//    
//    [GeTuiSdk startSdkWithAppId:GetuiAppId appKey:GetuiAppKey appSecret:GetuiAppSecret delegate:self];
//    // 判读系统版本是否是“iOS 10.0”以前
//    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 10.0 ||
//        [UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
//        // 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
//        UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
//        
//        // 定义用户通知设置
//        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
//        
//        // 注册用户通知 - 根据用户通知设置
//        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
//    } else { // iOS10.0 以后远程推送设置方式
//        // 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
////        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
//        
//        // 注册远程通知 -根据远程通知类型
////        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
//        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//        UNAuthorizationOptions options = UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert;
//        [center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) {
//            
//        }];
//    }
//}
//
///**
// *  处理收到的通知
// *
// *  @param userInfo <#notification description#>
// */
//- (void)openNotification:(NSDictionary*)userInfo addLocal:(BOOL)addLocal{
//    NSLog(@"openNotification  %@",userInfo);
//    NSDictionary *aps = userInfo[@"aps"];
//    UILocalNotification *_localNotifcation = [[UILocalNotification alloc] init];
//    _localNotifcation.soundName = aps[@"sound"];
//    _localNotifcation.fireDate=[NSDate dateWithTimeIntervalSinceNow:0];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"MessageProcessing" object:nil];
//    if(addLocal){
//        [self showMAddMessage:userInfo[@"aps"][@"alert"] userInfo:userInfo];
////        NSDictionary *aps = userInfo[@"aps"];
////        UILocalNotification *local = [[UILocalNotification alloc] init];
////        local.userInfo = userInfo;
////        //设置推送时间
////        local.fireDate=[NSDate dateWithTimeIntervalSinceNow:0];//立即触发
////        //设置本地通知的时区
////        local.timeZone = [NSTimeZone defaultTimeZone];
////        //推送声音
////        local.soundName = aps[@"sound"];
////        //内容
////        local.alertBody = aps[@"alert"];
////        //添加推送到uiapplication
////        UIApplication *app = [UIApplication sharedApplication];
////        local.applicationIconBadgeNumber = app.applicationIconBadgeNumber+1;
//////        [app scheduleLocalNotification:local];
////        [[UIApplication sharedApplication] presentLocalNotificationNow:local];
//        
//    }else{
//        [self openNotification:userInfo];
//    }
//}
//
//- (void)openNotification:(NSDictionary*)userInfo
//{
//    [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
//    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
//    [[UIApplication sharedApplication] cancelAllLocalNotifications];
//
//    NSDictionary *payload = userInfo[@"payload"];
//    if (payload && [payload isKindOfClass:[NSDictionary class]]) {
//        NSString *actUrl = payload[@"url"];
//        NSString *imageUrl = payload[@"img_url"];
//        if(actUrl && ![actUrl isEmpty]){
//            NSString * urlStr;
//            if([actUrl containsString:@"emergency"]){
//                NSRange range = [actUrl rangeOfString:@"id="];
//                NSString * idStr =[actUrl substringFromIndex:range.location + range.length];
//                urlStr =[NSString stringWithFormat:@"%@?emergency_id=%@",URL_AMapNaviWalkVC,idStr];
//            }else{
//                urlStr = actUrl;
//            }
//            [self openApplicationWithURL:[NSURL URLWithString:urlStr]];
//        }else if (imageUrl && ![imageUrl isEmpty]) {
////            self.needOpenUrl = [NSURL URLWithString:actUrl];
////            [self.advertView.AdImageView setImageWithURLString:imageUrl];
////            [self.advertView showAnimated:YES inView:self.window];
//        }
//    }
//}
//
//- (void)showMAddMessage:(NSString *)message userInfo:(id)userInfo{
//    MasterNotificationView* notificationView = [MasterNotificationView sharedInstance];
//    notificationView.userInfo = userInfo;
//    __weak AppDelegate* weakSelf = self;
//    [notificationView showMessageWithTitle:@"收到通知" description:message type:TWMessageBarMessageTypeInfo duration:3.0 callback:^{
//        [weakSelf openNotification:userInfo];
//    }];
////    [notificationView showMessageWithTitle:@"收到通知" description:message type:TWMessageBarMessageTypeInfo callback:^{
////        [weakSelf openNotification:userInfo];
////    }];
//}
//
//- (void)showMAddMessage:(NSString*)message{
//    [[MasterNotificationView sharedInstance] showMessageWithTitle:@"友情提醒"
//                                                      description:message
//                                                             type:TWMessageBarMessageTypeInfo
//                                                   statusBarStyle:UIStatusBarStyleLightContent
//                                                         callback:nil];
//}
//
//
//
//#pragma mark - APP运行中接收到通知(推送)处理
//
///** APP已经接收到“远程”通知(推送) - (App运行在后台/App运行在前台) */
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    [self openNotification:userInfo addLocal:application.applicationState==UIApplicationStateActive];
//    NSLog(@"\n>>>[Receive RemoteNotification]:%@\n\n", userInfo);
//}
//
//
///** APP已经接收到“远程”通知(推送) - 透传推送消息  */
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
//    
//    // 处理APN
//    NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n", userInfo);
//    
////    completionHandler(UIBackgroundFetchResultNewData);
//    [self openNotification:userInfo addLocal:application.applicationState==UIApplicationStateActive];
//}
//
//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
//{
//    [self openNotification:notification.userInfo addLocal:NO];
//}

#pragma mark - 

//- (void)createSpotlight{
//    if([[UIDevice systemVersion] floatValue]>=9.0){
//        NSMutableArray <CSSearchableItem *> *searchableItems = [NSMutableArray arrayWithCapacity:0];
//        for (NSInteger i=0;i<10;i++) {
//            NSString *title = [NSString stringWithFormat:@"Master title%d",i];
//            NSString *desc = [NSString stringWithFormat:@"Master desc %d",i];
//            NSString *time = [NSString stringWithFormat:@"2015 %d",i];;
//            NSString *nid = [NSString stringWithFormat:@"nid%d",i];;
//            CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc]initWithItemContentType:@"SearchAPIViews"];
//            attributeSet.title = title;
//            attributeSet.contentDescription = [NSString stringWithFormat:@"%@\n%@",desc,time];
//            NSMutableArray *keywords = [NSMutableArray arrayWithArray:[title componentsSeparatedByString:@" "]];
//            [keywords addObject:desc];
//            attributeSet.keywords = keywords;
//            NSString *identifiner = [NSString stringWithFormat:@"%@",nid];
//            [searchableItems addObject:[[CSSearchableItem alloc]initWithUniqueIdentifier:identifiner domainIdentifier:@"com.shishiTec.HiMaster" attributeSet:attributeSet]];
//        }
//        
//        [[CSSearchableIndex defaultSearchableIndex]indexSearchableItems:searchableItems completionHandler:^(NSError * __nullable error) {
//            if(error != nil){
//                NSLog(@"%@",error.localizedDescription);
//            }else {
//                NSLog(@"Items were indexed successfully");
//            }
//        }];
//    }
//}
//
//-(void) createItem
//{
//    if([[UIDevice systemVersion] floatValue]<9.0){
//        return;
//    }
//    //自定义icon 的初始化方法
//    //    UIApplicationShortcutIcon *icon1 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"your_icon"];
//    //    UIMutableApplicationShortcutItem *item0 = [[UIMutableApplicationShortcutItem alloc] initWithType:@"com.your.helloWorld" localizedTitle:@"Title" localizedSubtitle:@"sub Title" icon:icon1 userInfo:nil];
//    //这种是随意没有icon 的
//    UIMutableApplicationShortcutItem *item1 = [[UIMutableApplicationShortcutItem alloc] initWithType:@"test.com.A" localizedTitle:@"三条A"];
//    UIMutableApplicationShortcutItem *item2 = [[UIMutableApplicationShortcutItem alloc] initWithType:@"test.com.B" localizedTitle:@"三条B"];
//    UIMutableApplicationShortcutItem *item3 = [[UIMutableApplicationShortcutItem alloc] initWithType:@"test.com.C" localizedTitle:@"三条C"];
//    
//    NSArray *addArr = @[item2,item3,item1];
//    [UIApplication sharedApplication].shortcutItems = addArr;
//}
//
//- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void(^)(BOOL succeeded))completionHandler{
//    //判断先前我们设置的唯一标识
//    NSArray *arr = @[@"hello 3D Touch"];
//    UIActivityViewController *vc = [[UIActivityViewController alloc]initWithActivityItems:arr applicationActivities:nil];
//    //设置当前的VC 为rootVC
//    [self.window.rootViewController presentViewController:vc animated:YES completion:^{
//    }];
//}


#pragma mark --

//- (void)initAppConfig{
//   HttpManagerCenter* httpCenter = [HttpManagerCenter sharedHttpManager];
//    DBHelper *dbHelper = [DBHelper sharedDBHelper];
//    [[httpCenter getNewsWithpage:0 pageSize:10 resultClass:nil/*[AppConfigModel class]*/] subscribeNext:^(BaseModel *model) {
//        if (model.code == 200) {
//            AppConfigModel *configModel = model.data;
//            [dbHelper deleteClass:[CityModel class]];
//            [dbHelper insertModelArray:configModel.city_list];
//            [dbHelper deleteClass:[CategoryModel class]];
//            [dbHelper insertModelArray:configModel.category_list];
//            [dbHelper deleteClass:[SuperscriptModel class]];
//            [dbHelper insertModelArray:configModel.superscript_list];
//            [dbHelper deleteClass:[InterestModel class]];
//            [dbHelper insertModelArray:configModel.interest_list];
//            [dbHelper deleteClass:[OrderTypeModel class]];
//            [dbHelper insertModelArray:configModel.order_type];
//            [dbHelper deleteClass:[SelectTypeModel class]];
//            [dbHelper insertModelArray:configModel.select_type];
//            
//            [[UserClient sharedUserClient] setAppConfigUrl:configModel];
//            if (configModel.start_ads && [configModel.start_ads isKindOfClass:[NSDictionary class]] && configModel.start_ads.count>0) {
//                NSString *imageUrl = configModel.start_ads[@"pic_url"];
//                imageUrl = [imageUrl masterFullImageUrl];
//                [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageLowPriority|SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//                    
//                }];
//                [NSUserDefaults setObject:configModel.start_ads forKey:StartAppAdKey];
//            }else{
//                [NSUserDefaults removeObjectWithKey:StartAppAdKey];
//            }
//            if (configModel.start_small_ads && [configModel.start_small_ads isKindOfClass:[NSDictionary class]] && configModel.start_small_ads.count>0) {
//                
//                NSString *cacheAdIds = [NSUserDefaults stringForKey:StartAppAlertAdIdsKey];
//                NSString *curAdId = [NSString stringWithFormat:@"%@,",configModel.start_small_ads[@"ads_data_id"]];
//                if (cacheAdIds==nil || [cacheAdIds rangeOfString:curAdId].location ==NSNotFound) {
//                    NSString *imageUrl = configModel.start_ads[@"pic_url"];
//                    imageUrl = [imageUrl masterFullImageUrl];
//                    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageLowPriority|SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//                    }];
//                    [NSUserDefaults setObject:[NSString stringWithFormat:@"%@%@",cacheAdIds,curAdId] forKey:StartAppAlertAdIdsKey];
//                    [NSUserDefaults setObject:configModel.start_small_ads forKey:StartAppAlertAdKey];
//                }
//            }
//        }
//    }];
//}

//- (void)showAppAdView{
//    if (self.appNewVersion) {//新版本不投放广告。
//        return;
//    }
//    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
//
//    id adAlterData = [userDefaults objectForKey:StartAppAlertAdKey];
//    if (adAlterData) {
//        NSString *pfurl = adAlterData[@"pfurl"];
//        if(pfurl && ![pfurl isEmpty]){
//            self.needOpenUrl = [NSURL URLWithString:adAlterData[@"pfurl"]];
//        }
//        self.advertView.adData = adAlterData;
//        [self.advertView.AdImageView setImageWithURLString:adAlterData[@"pic_url"]];
//        [self.advertView showAnimated:YES inView:self.window];
//        [userDefaults removeObjectForKey:StartAppAlertAdKey];
//        return ;
//    }
//    
//    id adData = [userDefaults objectForKey:StartAppAdKey];
//    if (adData && [adData isKindOfClass:[NSDictionary class]]) {
//        AppAdView* addAdView = [AppAdView loadInstanceFromNib];
//        addAdView.adData = adData;
//        [addAdView.adImageView setImageWithURLString:adData[@"pic_url"]];
//        addAdView.frame = self.window.bounds;
//        [self.window addSubview:addAdView];
//        addAdView.appAdViewBlock = ^(id data){
//            if (data) {
//                NSString *pfurl = data[@"pfurl"];
//                if(pfurl && ![pfurl isEmpty]){
//                    [self performSelector:@selector(openApplicationWithURL:) withObject:[NSURL URLWithString:data[@"pfurl"]] afterDelay:1];
//                }
//            }else{
//                
//            }
//        };
//    }
//}
//#pragma -- RealReachability
//-(void)startDetectCurrentReachabilityStatus{
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(networkChanged:)
//                                                 name:kRealReachabilityChangedNotification
//                                               object:nil];
//    ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
//    NSLog(@"Initial reachability status:%@",@(status));
//    if (status == RealStatusNotReachable)
//    {
////        [self showSettingAlert];
////        [[MasterUrlManager shareMasterUrlManager].currentVC showHUDWithString:@"网络连接不稳定！！！"];
//    }
//}
//- (void)networkChanged:(NSNotification *)notification
//{
//    RealReachability *reachability = (RealReachability *)notification.object;
//    ReachabilityStatus status = [reachability currentReachabilityStatus];
//    ReachabilityStatus previousStatus = [reachability previousReachabilityStatus];
//    NSLog(@"networkChanged, currentStatus:%@, previousStatus:%@", @(status), @(previousStatus));
//    if (status == RealStatusNotReachable)
//    {
////        [self showSettingAlert];
////        [[MasterUrlManager shareMasterUrlManager].currentVC hiddenHUDWithString:@"无网络连接" error:YES];
//    }else{
////        [[MasterUrlManager shareMasterUrlManager].currentVC hiddenHUDWithString:@"已恢复连接网络" error:YES];
//    }
//}
//-(void)showSettingAlert{
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"关闭飞行模式或者使用无线局域网来访问数据" delegate:self cancelButtonTitle:@"好" otherButtonTitles:@"设置", nil];
//    [alertView.rac_buttonClickedSignal subscribeNext:^(NSNumber *x) {
//        if (x.intValue==1) {
////            [[UIApplication sharedApplication] openURL:nil options:nil completionHandler:nil];
//            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=AIRPLANE_MODE"]];
//        }
//    }];
//    [alertView show];
//}

//#pragma -- AMapLocationManager
//- (AMapLocationManager *)locationManager{
//    if (!_locationManager) {
//        _locationManager = [[AMapLocationManager alloc] init];
//        _locationManager.delegate=self;
//    }
//    return _locationManager;
//}
//
//- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
//{
//    self.canLocation =YES;
//    [[MasterNotificationView sharedInstance] hideAllAnimated:YES];
//    self.locationLat=  [NSString stringWithFormat:@"%f",location.coordinate.latitude];
//    self.locationLng=  [NSString stringWithFormat:@"%f",location.coordinate.longitude];
//    self.accuracy=  [NSString stringWithFormat:@"%f",location.horizontalAccuracy];
////    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
//}
//- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error{
//    NSString * message =@"请允许我们使用您的位置，保证您的安全";
//    NSLog(@"Error: %@",[error localizedDescription]);
//    switch([error code]) {
//        case kCLErrorDenied:
//            self.canLocation =NO;
//            [[MasterNotificationView sharedInstance] showMessageWithTitle:@"友情提醒" description:message type:TWMessageBarMessageTypeInfo
//                                                                 duration:MAXFLOAT statusBarStyle:UIStatusBarStyleLightContent callback:^(void){
//                                                                     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//                                                                 }];
//            break;
//        default:
//            break;
//    }
//
//
//}
//- (void)startSerialLocation
//{
//    //开始定位
//    self.locationManager.delegate=self;
//    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
//    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
//    [self.locationManager startUpdatingLocation];
//}
//
//#pragma mark -- 注册Url 路由
//
//- (void)registerUrl{
//    MasterUrlManager *urlManager = [MasterUrlManager shareMasterUrlManager];
////    [urlManager addStoryboardName:@"NewsClue"];
//    [urlManager addStoryboardName:@"GuardMe"];
//    [urlManager addStoryboardName:@"Mine"];
////    [urlManager addStoryboardName:@"HelpMe"];
//    [urlManager addStoryboardName:@"LoginTo"];
//
//    [urlManager setViewControllerName:@"GPSNaviViewController" forURL:URL_AMapNaviWalkVC];
//    [urlManager setViewControllerName:@"LoginToNavigationController" forURL:URL_MasterLoginRoot];
//    [urlManager setViewControllerName:@"LoginSecurityCodeVC" forURL:URL_YihubangSetSecurityCode];
//    [urlManager setViewControllerName:@"PreLoginViewController" forURL:URL_UserLoginRoot];
//}

#pragma mark -- 
- (void)openAppMainVCT
{
    UIViewController *mainVct;
    self.appRunning = YES;
//    if(![UserClient sharedUserClient].rawLogin){
//        //跳转进登录注册页面
//        mainVct = [UIStoryboard viewController:@"LoginTo" identifier:@"LoginToNavigationController"];
//        self.manuLogin = YES;
//    }
//    /* 设置了隐私密码、第一次打开App、前一步操作是登陆 */
//    else if ([UserClient sharedUserClient].password.length == 4 && self.appFirstRun == YES && [UserClient sharedUserClient].userLoginInfo == nil) {
//        mainVct = [UIStoryboard viewController:@"Mine" identifier:@"AlterSecurityCideViewController"];
//        self.appFirstRun = NO;
//        /* 如果用户信息里性别为0时 */
//    }else if ([[UserClient sharedUserClient].userInfo[@"sex"] isEqualToString:@"0"]) {
//        mainVct = [UIStoryboard viewController:@"LoginTo" identifier:@"SexSelectionViewController"];
//    }else {
//        /* 进入首页 */
//        mainVct = [UIStoryboard viewController:@"Main" identifier:@"TabBarViewController"];
////        mainVct = [UIStoryboard viewController:@"GuardMe" identifier:@"SlideMainViewController"];
//    }
    mainVct = [UIStoryboard viewController:@"Main" identifier:@"TabBarViewController"];
    
    self.window.rootViewController = mainVct;
//    if(self.needOpenUrl){
//        [self performSelector:@selector(openApplicationWithURL:) withObject:self.needOpenUrl afterDelay:1];
//        self.needOpenUrl = nil;
//    }else if (self.needNotificationInfo){
//        [self performSelector:@selector(openNotification:) withObject:self.needNotificationInfo afterDelay:1];
//        self.needNotificationInfo = nil;
//    }else{
//        [self showAppAdView];
//    }
}

#pragma mark -- 广告处理

//- (AdvertisementView*)advertView{
//    if (!_advertView) {
//        _advertView = [AdvertisementView loadInstanceFromNib];
//        _advertView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.8f];
////        _advertView.cornerRadius = 6.0f;
//        @weakify(self);
//        [_advertView.AdImageView setTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
//            @strongify(self);
//            [self.advertView hiddenAnimated:YES];
//            [self openApplicationWithURL:self.needOpenUrl];
//        } ];
//    }
//    return _advertView;
//}

#pragma mark - WXApiDelegate

//-(void) onReq:(BaseReq*)res
//{
//    
//}
//-(void) onResp:(BaseResp*)resp
//{
//    if([resp isKindOfClass:[PayResp class]]){
//        //支付返回结果，实际支付结果需要去微信服务器端查询
//        NSString *strMsg = [NSString stringWithFormat:@"支付结果"];
//        switch (resp.errCode) {
//            case WXSuccess:
//                [self paySuccess:3];
//                break;
//            case WXErrCodeUserCancel:
//                
//                break;
//            case WXErrCodeCommon:
//                
//                break;
//            case WXErrCodeSentFail:
//                
//                break;
//            case WXErrCodeAuthDeny:
//                
//                break;
//            case WXErrCodeUnsupport:
//                
//                break;
//            default:
//                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
//                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
//                break;
//        }
//    }
//}
#pragma mark -- GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    [NSUserDefaults setArcObject:clientId forKey:APP_GetuiToken_Key];
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}

/** SDK遇到错误回调 */
//- (void)GeTuiSdkDidOccurError:(NSError *)error {
//    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
//    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
//    [self registerRemoteNotification];
//
//}


/** SDK收到透传消息回调 */
//- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
//    // [4]: 收到个推消息
//    NSString *payloadMsg = nil;
//    if (payloadData) {
//        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
//        NSDictionary *payload = [self formatGetuiMsg:payloadMsg];
//        NSMutableDictionary *spn = [[NSMutableDictionary alloc] init];
//        NSMutableDictionary *alert = [[NSMutableDictionary alloc] init];
//        if(payload && payload[@"content"])
//        [alert setObject:payload[@"content"] forKey:@"alert"];
//        [spn setObject:alert forKey:@"aps"];
//        [spn setObject:payload forKey:@"payload"];
//        [self openNotification:spn addLocal:YES];
//    }
//    
//    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@", taskId, msgId, payloadMsg, offLine ? @"<离线消息>" : @""];
//    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
//}
/** SDK收到sendMessage消息回调 */
//- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
//    // [4-EXT]:发送上行消息结果反馈
//    NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
//    NSLog(@"\n>>>[GexinSdk DidSendMessage]:%@\n\n", msg);
//}
///** SDK运行状态通知 */
//- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
//    // [EXT]:通知SDK运行状态
//    NSLog(@"\n>>>[GexinSdk SdkState]:%u\n\n", aStatus);
//}
///** SDK设置推送模式回调 */
//- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
//    if (error) {
//        NSLog(@"\n>>>[GexinSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
//        return;
//    }
//    NSLog(@"\n>>>[GexinSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
//}
-(NSDictionary*)formatGetuiMsg:(NSString*)msg{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    msg =  [msg stringByReplacingOccurrencesOfString:@"{" withString:@""];
    msg =  [msg stringByReplacingOccurrencesOfString:@"}" withString:@""];
    NSArray *array = [msg componentsSeparatedByString:@","];
    for(NSString *str in array){
        NSRange range = [str rangeOfString:@"="];
        if(range.location != NSNotFound){
            NSString *key = [str substringToIndex:range.location];
            NSString *value = [str substringFromIndex:range.location+1];
            [dic setObject:value forKey:[key stringByReplacingOccurrencesOfString:@" " withString:@""] ];
        }
    }
    return dic;
}

@end
